<template>
  <view class="containerzi">
    <view @click="openPopup()">
      <view style="margin-bottom: 8rpx;">
        <text class="required-star">*</text>
        售后发起日期
      </view>
      <up-input placeholder="售后发起日期" border="surround" v-model="value"
        :customStyle="{ width: '90vw', pointerEvents: 'none', backgroundColor: ' #ffffff' }" readonly
        @click="openPopup()"></up-input>
    </view>

    <!--  日期选择器  -->
    <up-datetime-picker title="选择售后发起日期" :show="show" v-model="dateValue" mode="date" @confirm="confirm"
      :closeOnClickOverlay="true" @close="closePopup" @cancel="show = false"></up-datetime-picker>

    <!--  订单-客户信息  -->
    <view>
      <view style="margin-bottom: 8rpx;margin-top: 30rpx;">
        <text class="required-star">*</text>
        订单-客户信息
      </view>
      <view>
        <scroll-view scroll-x="true" class="scroll-view">
          <view class="table-container">
            <table class="mobile-table order-table">
              <thead>
                <tr>
                  <!-- <th class="sticky-header">序号</th> -->
                  <th v-for="(item, index) in orderList" :key="index" class="nowrap">
                    <view style="display:flex;">
                      <text v-if="item.required" class="required-star">*</text>
                      <view>{{ item.title }}</view>
                    </view>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, rowIndex) in tableData" :key="rowIndex" @click="clickorder(row, rowIndex)">
                  <!-- <td class="sticky-col">{{ rowIndex + 1 }}</td> -->
                  <td v-for="(header, colIndex) in orderList" :key="colIndex" class="nowrap"
                    :class="{ highlight: header.field === 'orderNum' }">
                    {{ row[header.field] }}
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 产品信息  -->
    <view style="background-color: #ffffff">
      <view style="margin-bottom: 8rpx;margin-top: 30rpx;">
        <text class="required-star">*</text>
        产品信息
      </view>
      <view>
        <scroll-view scroll-x="true" class="scroll-view">
          <view class="table-container">
            <table class="mobile-table">
              <thead>
                <tr>
                  <!-- <th class="sticky-header">序号</th> -->
                  <th v-for="(header, index) in visibleProductColumns" :key="index" class="nowrap">
                    <view style="display:flex;">
                      <text v-if="header.required" class="required-star">*</text>
                      <view>{{ header.title }}</view>
                    </view>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, rowIndex) in productData" :key="rowIndex" @click="clickproduct(row, rowIndex)">
                  <!-- <td class="sticky-col">{{ rowIndex + 1 }}</td> -->
                  <td v-for="(header, colIndex) in visibleProductColumns" :key="colIndex" class="nowrap">
                    {{ row[header.field] }}
                  </td>
                </tr>
              </tbody>
            </table>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 
    <view>
      <view style="margin-bottom: 8rpx;margin-top: 30rpx;">
        上传附件
      </view>
      <FileUpload @orderAfterSales="orderAfterSalesFile" />
    </view>

    <view>
      <view style="margin-bottom: 8rpx;margin-top: 30rpx;">
        备注
      </view>
      <textarea ref="textarea" auto-height v-model="Aftersalesorderremarks" placeholder="请输入备注"
        @input="onTextareaInput" />
    </view> -->
    <!-- 订单列表弹窗 -->
    <up-popup :z-index="99999" :show="showOrderListPopup" mode="right" @close="showOrderListPopup = false"
      :customStyle="{ height: '100vh', width: '100vw', borderRadius: '16rpx 0 0 16rpx' }">
      <up-navbar title="选择订单" @leftClick="showOrderListPopup = false" placeholder
        :customStyle="{ backgroundColor: '#fff', borderBottom: '1px solid #f5f5f5' }"></up-navbar>
      <view class="search-box">
        <u-input v-model="searchKeyword" placeholder="输入订单号或客户名称搜索" clearable @change="handleSearchInput"></u-input>
      </view>
      <view class="popup-containerd">

        <!-- #ifdef H5 -->
        <view style="height: 20rpx"></view>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS -->
        <view style="height: 20rpx"></view>
        <!-- #endif -->

        <scroll-view scroll-y class="popup-scroll" @scrolltolower="loadMoreOrders">
          <view v-for="(order, index) in filteredOrders" :key="order.id" class="order-item"
            @click="selectOrderItem(order)">
            <view class="order-info">
              <text class="order-label">订单编号：</text>
              <text class="order-value">{{ order.order_sum }}</text>
            </view>
            <view class="order-arrow">
              <u-icon name="arrow-right" color="#999" size="16"></u-icon>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <!-- 选择订单弹出层 -->
    <up-popup :show="showOrderPopup" mode="right" @close="showOrderPopup = false">
      <view class="popup-container">
        <up-navbar :placeholder="false" :title="'订单信息 第' + (currentRowIndex + 1) + '行数据'"
          @leftClick="showOrderPopup = false" placeholder></up-navbar>
        <!-- #ifdef H5 -->
        <view style="height: 60rpx"></view>
        <!-- #endif -->

        <!-- #ifdef APP-PLUS -->
        <view style="height: 9vh"></view>
        <!-- #endif -->
        <scroll-view scroll-y class="popup-scroll">
          <view class="popup-content">
            <up-form :model="currentOrder" :rules="orderRules" ref="orderForm" label-position="top">
              <up-form-item v-for="item in orderList" :key="item.field" :label="item.title" :required="item.required"
                :prop="item.field">
                <!-- <up-input :disabled="item.disabled" @click="item.field === 'orderNum' ? openOrderListPopup() : null"
                  v-model="currentOrder[item.field]" :placeholder="`请输入${item.title}`"></up-input> -->


                <template v-if="item.field === 'arrivalDate'">
                  <view @click="showArrivalDatePicker = true">
                    <!-- 日期选择器 -->
                    <up-datetime-picker v-model="arrivalDateTemp" mode="date" :show="showArrivalDatePicker"
                      title="选择到货日期" @confirm="handleArrivalDateConfirm" @close="showArrivalDatePicker = false"
                      @cancel="showArrivalDatePicker = false"></up-datetime-picker>
                    <!-- 触发按钮 -->
                    <up-input :customStyle="{ width: '86vw', pointerEvents: 'none', backgroundColor: ' #ffffff' }"
                      @click="showArrivalDatePicker = true" readonly v-model="currentOrder.arrivalDate"
                      placeholder="请选择到货日期"></up-input>
                  </view>
                </template>

                <template v-else>
                  <up-input :disabled="item.disabled" @click="item.field === 'orderNum' ? openOrderListPopup() : null"
                    v-model="currentOrder[item.field]" :placeholder="`请输入${item.title}`"></up-input>
                </template>

              </up-form-item>
            </up-form>
            <up-button type="primary" @click="validateOrderForm" style="margin-bottom: 20rpx">保存</up-button>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <!-- 产品信息 -->
    <up-popup :show="showProductEditPopup" mode="right" @close="showProductEditPopup = false">
      <view class="popup-container">
        <up-navbar :placeholder="false" :title="'产品信息 第' + (currentRowIndex + 1) + '行数据'"
          @leftClick="showProductEditPopup = false" placeholder></up-navbar>
        <!-- #ifdef APP-PLUS -->
        <view style="height: 9vh"></view>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <view style="height: 60rpx"></view>
        <!-- #endif -->
        <view class="popup-header-fixed">产品信息</view>
        <scroll-view scroll-y class="popup-scroll">
          <view class="popup-content">
            <!--            :rules="productRules" -->
            <up-form :model="currentProduct" :rules="productRules" ref="productForm" label-position="top">
              <up-form-item v-for="item in filteredProductList" :key="item.field" :label="item.title"
                :required="item.required" :prop="item.field">
                <!-- 处理方式单选框 -->
                <up-radio-group v-if="item.type === 'radio'" v-model="currentProduct[item.field]">
                  <up-radio v-for="option in item.options" :key="option.value" :label="option.label"
                    :name="option.value" @change="radiochange"></up-radio>
                </up-radio-group>
                <!-- 其他输入项 -->
                <up-input v-else :disabled="item.disabled" v-model="currentProduct[item.field]"
                  :placeholder="`请输入${item.title}`"></up-input>
              </up-form-item>
            </up-form>
            <up-button type="primary" @click="validateProductForm" style="margin-bottom: 20rpx">保存</up-button>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script>
import { BaseDatagylList, GetgylList } from '@/apis/SupplyChain/orderAfterSales';
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';
import FileUpload from '../components/FileUpload.vue';
export default {
  name: "orderAfterSales",
  props: {
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data () {
    return {
      modalShow: false,
      show: false,
      dateValue: Number(new Date()),
      dateMode: '',
      value: '',
      orderList: [
        {
          title: '订单编号',
          field: 'orderNum',
          required: true
        },
        {
          title: '发起日期',
          field: 'pickDate',
          required: true,
          disabled: true
        },
        {
          title: '所属部门',
          field: 'department',
          required: true,
          disabled: true
        },
        {
          title: '销售人员',
          field: 'salesPerson',
          required: true,
          disabled: true
        },
        {
          title: '客户名称',
          field: 'customerName',
          required: true,
          disabled: true
        },
        {
          title: '到货日期',
          field: 'arrivalDate',
          required: true,
          showPicker: false
        },
        {
          title: '备注',
          field: 'notes'
        }
      ], // 订单-客户信息
      tableData: [
        {
          notes: '',
        },

      ], // 订单-客户信息
      productList: [
        {
          title: '发货园区',
          field: 'parkName',
          required: true
        },
        {
          title: '产品名称',
          field: 'productName',
          required: true,
          disabled: true
        },
        {
          title: 'SKU名称',
          field: 'skuName',
          required: true
        },
        {
          title: '原订单数（箱/件）',
          field: 'piece',
          required: true
        },
        {
          title: '原订单重量（kg）',
          field: 'grossWeight',
          required: true
        },
        {
          title: '箱规（最小规格数量）',
          field: 'weight',
          required: true
        },
        {
          title: '原订单单价（元/kg）',
          field: 'desc',
          required: true
        },
        {
          title: '处理方式',
          field: 'saleType',
          required: true,
          type: 'radio', // 标记为单选框类型
          options: [
            { label: '退货', value: '退货' },
            { label: '折价', value: '折价' }
          ]
        },
        {
          title: '售后重量(kg)',
          field: 'compensationQuantity',
          required: true,
          show: false // 新增显示控制
        },
        {
          title: '折价后单价(元/kg)）',
          field: 'discountPrice',
          required: true,
          show: false // 新增显示控制
        },
        {
          title: '最终应付金额(元)',
          field: 'actualPayableAmount',
          required: true,
          show: false,
          disabled: true
        },
        {
          title: '备注',
          field: 'reason'
        }
      ], // 产品信息
      productData: [
        {
          reason: ''
        },
      ],
      // 订单选择列表
      orderOptions: [],
      // 弹出层控制
      showOrderPopup: false,
      showOrderEditPopup: false,
      showProductEditPopup: false,
      // 当前操作的数据
      currentRowIndex: null,
      // 订单校验规则
      orderRules: {
        orderNum: [{ required: true, message: '请输入订单编号', trigger: 'change' }],
        pickDate: [{ required: true, message: '请输入发起日期', trigger: 'change' }],
        department: [{ required: true, message: '请输入所属部门', trigger: 'change' }],
        salesPerson: [{ required: true, message: '请输入销售人员', trigger: 'change' }],
        customerName: [{ required: true, message: '请输入客户名称', trigger: 'change' }],
        arrivalDate: [{ required: true, message: '请输入到货日期', trigger: 'change' }]
      },
      // 产品校验规则
      productRules: {
        parkName: [{ required: true, message: '请输入发货园区', trigger: 'change' }],
        productName: [{ required: true, message: '请输入产品名称', trigger: 'change' }],
        skuName: [{ required: true, message: '请输入SKU名称', trigger: 'change' }],
        piece: [{ required: true, message: '请输入原订单数', trigger: 'change' }],
        grossWeight: [{ required: true, message: '请输入原订单重量', trigger: 'change' }],
        weight: [{ required: true, message: '请输入箱规', trigger: 'change' }],
        desc: [{ required: true, message: '请输入原订单单价', trigger: 'change' }],
        saleType: [{ required: true, message: '请输入处理方式', trigger: 'change' }],
        compensationQuantity: [{ required: true, message: '请输入售后重量', trigger: 'change' }],
        discountPrice: [{ required: true, message: '请输入折价后单价', trigger: 'change' }],
        actualPayableAmount: [{ required: true, message: '请输入最终应付金额', trigger: 'change' }]
      },
      // 初始化当前订单数据
      currentOrder: {
        orderNum: '',
        pickDate: '',
        department: '',
        salesPerson: '',
        customerName: '',
        arrivalDate: '',
        notes: ''
      },
      // 初始化当前产品数据
      currentProduct: {
        parkName: '',
        productName: '',
        skuName: '',
        piece: '',
        grossWeight: '',
        weight: '',
        desc: '',
        saleType: '退货', // 默认退货
        compensationQuantity: '',
        discountPrice: '',
        actualPayableAmount: '',
        reason: ''
      },
      pageNum: 1,
      pageSize: 15,
      total: 0,
      allGylorderNO: [],
      showOrderListPopup: false,
      isLoadingOrders: false,
      noMoreOrders: false,
      searchKeyword: '',
      tempOrderData: null,
      tempProductData: null,
      Aftersalesorderremarks: '',
      showArrivalDatePicker: false,
      arrivalDateTemp: Date.now(), // 临时存时间戳
    }
  },
  components: {
    FileUpload
  },
  watch: {
    'currentProduct.compensationQuantity': {
      handler (newVal) {
        if (this.currentProduct.saleType === '折价') {
          this.calculateActualPayable(this.currentProduct);
        }
      },
      deep: true
    },
    'currentProduct.discountPrice': {
      handler (newVal) {
        if (this.currentProduct.saleType === '折价') {
          this.calculateActualPayable(this.currentProduct);
        }
      },
      deep: true
    }
  },
  created () {
    uni.setStorageSync('orderAfterSalesData', null);
    // this.gGetgylList()

    uni.$on('orderAfterSales', (order) => {
      this.selectOrderItem(order)
    })

    this.handleDataEcho()
  },

  computed: {
    ...mapStores(useUserStore),
    filteredProductList () {
      return this.productList.filter(item => {
        if (!item) return false;
        if (['compensationQuantity', 'discountPrice', 'actualPayableAmount'].includes(item.field)) {
          return this.currentProduct.saleType === '折价';
        }
        return true;
      });
    },
    visibleProductColumns () {
      return this.productList.filter(header => {
        if (!header) return false;

        // 总是显示的列
        const alwaysShow = ['parkName', 'productName', 'skuName', 'piece', 'grossWeight', 'weight', 'desc', 'saleType', 'reason'];
        if (alwaysShow.includes(header.field)) return true;

        // 根据 saleType 决定是否显示的列
        const discountOnly = ['compensationQuantity', 'discountPrice', 'actualPayableAmount'];
        if (discountOnly.includes(header.field)) {
          // 检查当前是否有选中行，或者默认显示逻辑
          return this.currentProduct?.saleType === '折价' ||
            this.productData.some(row => row.saleType === '折价');
        }

        return false;
      });
    },
    filteredOrders () {
      if (!this.searchKeyword) {
        return this.allGylorderNO; // 没有搜索关键词时返回全部数据
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.allGylorderNO.filter(order => {
        return (
          (order.order_sum && order.order_sum.toLowerCase().includes(keyword)) ||
          (order.customer_name && order.customer_name.toLowerCase().includes(keyword))
        );
      });
    }
  },
  methods: {
    handleDataEcho () {
      if (!this.ApplyDetailList.formData) return;
      const fieldValue = this.ApplyDetailList.formData[this.config.id];
      this.value = fieldValue.afterSaleDate;
      this.tableData = fieldValue.orderList || [];
      this.productData = fieldValue.productList || [];

      this.currentOrder = this.tableData.length > 0 ? { ...this.tableData[0] } : {
        orderNum: '',
        pickDate: '',
        department: '',
        salesPerson: '',
        customerName: '',
        arrivalDate: '',
        notes: ''
      };

      this.currentProduct = this.productData.length > 0 ? { ...this.productData[0] } : {
        parkName: '',
        productName: '',
        skuName: '',
        piece: '',
        grossWeight: '',
        weight: '',
        desc: '',
        saleType: '退货',
        compensationQuantity: '',
        discountPrice: '',
        actualPayableAmount: '',
        reason: ''
      };

      this.updateLocalStorage();
    },

    handleArrivalDateConfirm (e) {
      const date = this.formatTimestampToYYMMDD(e.value) // 复用已有的格式化方法
      this.currentOrder.arrivalDate = date
      this.showArrivalDatePicker = false
    },
    handleSearchInput () {
      // 重置分页参数
      this.pageNum = 1;
      this.noMoreOrders = false;

      // 如果有搜索关键词，使用本地过滤
      if (this.searchKeyword) {
        return;
      }

      // 没有搜索关键词时重新加载数据
      this.allGylorderNO = [];
      this.loadMoreOrders();
    },
    // 打开弹窗时重置分页
    openOrderListPopup () {
      uni.navigateTo({
        url: `/pages/apply/form/components/showOrderListPopup?SupplyChain=orderAfterSales`
      });

      // this.pageNum = 1
      // this.allGylorderNO = []
      // this.noMoreOrders = false
      // this.showOrderListPopup = true
      // this.loadMoreOrders()
    },

    async loadMoreOrders () {
      // 如果有搜索关键词，不执行上拉加载
      if (this.searchKeyword) return;
      // 防止重复加载或已加载全部
      if (this.isLoadingOrders || this.noMoreOrders) return;

      this.isLoadingOrders = true;
      try {
        const res = await GetgylList({
          token: this.userStore.user.token,
          type: 1,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNumber: ''
        });

        if (res.status == 1) {
          // 确保数据格式正确
          const records = res.data?.records || [];
          this.total = res.data?.total || 0;

          // 处理第一页加载的情况
          if (this.pageNum === 1) {
            this.allGylorderNO = records;
          } else {
            this.allGylorderNO.push(...records);
          }

          // 判断是否还有更多数据
          if (records.length < this.pageSize || this.allGylorderNO.length >= this.total) {
            this.noMoreOrders = true;
          } else {
            this.pageNum += 1;
          }
        } else {
          uni.showToast({
            title: res.message || '加载失败',
            icon: 'none'
          });
        }
        this.modalShow = false
      } catch (err) {
        this.modalShow = false
        console.error('加载订单列表失败:', err);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.modalShow = false
        this.isLoadingOrders = false;
      }
    },
    // 选中订单
    selectOrderItem (order) {
      this.searchKeyword = ''
      // 将选中的订单数据填充到当前编辑的订单表单中
      this.currentOrder = {
        ...this.currentOrder,
        orderNum: order.order_sum || '', // 订单编号
      };
      this.gBaseDatagylList(order.order_sum)
      // 关闭订单选择弹窗
      this.showOrderListPopup = false;
    },
    async gBaseDatagylList (value) {
      try {
        this.modalShow = true;
        const res = await BaseDatagylList({
          token: this.userStore.user.token,
          type: 2,
          orderNum: value,
        });

        if (res.status === 1 && res.data) {
          const orderData = res.data;

          // 暂存订单数据到临时变量
          this.tempOrderData = {
            orderNum: orderData.orderSum || '',
            pickDate: orderData.pickDate || '',
            department: orderData.department || '',
            salesPerson: orderData.salesPerson || '',
            customerName: orderData.customerName || '',
            arrivalDate: orderData.arrivalDate || '',
            notes: '',
          };

          // 暂存产品数据到临时变量
          this.tempProductData =
            orderData.items && orderData.items.length > 0
              ? orderData.items.map((item) => ({
                belongId: item.belongId,
                parkName: item.companyName,
                productName: item.productName || '',
                skuName: item.skuName || '',
                piece: item.piece ? String(item.piece) : '',
                grossWeight: item.weightTotal || '',
                weight: item.weight || '',
                desc: item.desc || '',
                saleType: '退货',
                compensationQuantity: '',
                discountPrice: '',
                actualPayableAmount: '',
                reason: '',
                show: false, // 添加这个字段
              }))
              : [];

          console.log(this.tempProductData);
          // 更新当前订单表单数据（仅用于显示）
          this.currentOrder = { ...this.tempOrderData };
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
      } finally {
        this.modalShow = false;
      }
    },

    // 处理单选框变化
    radiochange (e) {
      this.currentProduct.saleType = e;

      // 设置显示状态
      const shouldShow = e === '折价';
      this.currentProduct.show = shouldShow;

      // 如果是折价，初始化字段
      if (e === '折价') {
        this.currentProduct.compensationQuantity = this.currentProduct.compensationQuantity || '';
        this.currentProduct.discountPrice = this.currentProduct.discountPrice || '';
        this.calculateActualPayable(this.currentProduct);
      } else {
        // 如果是退货，清空相关字段
        this.currentProduct.compensationQuantity = '';
        this.currentProduct.discountPrice = '';
        this.currentProduct.actualPayableAmount = '';
      }
    },
    // 计算最终应付金额
    calculateActualPayable (row) {
      console.log('计算实际应付金额 - 入参:', row);
      if (row.saleType === '折价' &&
        row.compensationQuantity !== undefined &&
        row.compensationQuantity !== null &&
        String(row.compensationQuantity).trim() !== '' && // 兼容字符串/数字类型的空值
        row.discountPrice !== undefined &&
        row.discountPrice !== null &&
        String(row.discountPrice).trim() !== '' &&
        row.desc !== undefined &&
        row.desc !== null &&
        String(row.desc).trim() !== '' &&
        row.grossWeight !== undefined &&
        row.grossWeight !== null &&
        String(row.grossWeight).trim() !== ''
      ) {
        try {
          // 统一转成数字（避免字符串拼接/类型错误）
          const grossWeight = parseFloat(row.grossWeight); // 总重量
          const originalUnitPrice = parseFloat(row.desc); // 原订单单价（元/kg）
          const discountUnitPrice = parseFloat(row.discountPrice); // 折价后单价（元/kg）
          const compensationQuantity = parseFloat(row.compensationQuantity); // 补偿数量

          // 边界值校验：重量/单价不能为0或负数
          if (grossWeight <= 0 || originalUnitPrice <= 0 || compensationQuantity < 0) {
            row.actualPayableAmount = "0.00";
            console.warn('计算警告：重量/单价为0或负数，返回0', row);
            return;
          }

          // 核心公式（和PC端一致：原价总金额 - 折价优惠金额）
          const originalTotal = grossWeight * originalUnitPrice; // 原价总金额
          const discountPart = compensationQuantity * (originalUnitPrice - discountUnitPrice); // 折价优惠金额
          const actualPayable = originalTotal - discountPart; // 实际应付金额

          // 结果处理：保留2位小数，避免负数（优惠超原价时按0计算）
          row.actualPayableAmount = Math.max(actualPayable, 0).toFixed(2);
          console.log('计算成功:', {
            originalTotal,
            discountPart,
            actualPayable: row.actualPayableAmount
          });
        } catch (error) {
          console.error('计算实际应付金额错误:', error, '入参:', row);
          row.actualPayableAmount = "0.00"; // 异常时默认0
        }
      } else {
        // 条件不满足时，默认应付金额为0
        row.actualPayableAmount = "0.00";
        console.warn('计算条件不满足，返回0', row);
      }
    },
    openPopup () {
      this.show = true;
    },
    closePopup () {
      this.show = false;
    },
    // 选中时间
    confirm (event) {
      var date = this.formatTimestampToYYMMDD(event.value);
      this.value = date;
      this.show = false;

      // 更新本地缓存并通知父组件
      this.updateLocalStorage();
    },
    // 更新本地缓存并通知父组件
    updateLocalStorage () {
      const cachedData = {
        orderList: this.tableData,
        productList: this.productData,
        afterSaleDate: this.value,
      };

      uni.setStorageSync('orderAfterSalesData', cachedData);

      // 触发事件通知父组件数据已更新
      this.$emit('data-updated', cachedData);
    },
    // 打开选择订单弹窗
    openOrderSelect () {
      this.showOrderPopup = true
    },

    // 选择订单
    selectOrder (order) {
      this.tableData = [order]
      this.showOrderPopup = false
    },

    // 点击订单行
    clickorder (row, rowIndex) {
      this.currentOrder = {
        ...this.currentOrder, // 保留初始化结构
        ...row // 覆盖实际数据
      }
      this.currentRowIndex = rowIndex
      this.showOrderPopup = true
    },

    // 点击产品行
    clickproduct (row, rowIndex) {
      this.currentRowIndex = rowIndex;
      // 深拷贝当前行数据
      this.currentProduct = JSON.parse(JSON.stringify(row));

      // 初始化显示状态
      this.currentProduct.show = this.currentProduct.saleType === '折价';

      // 如果是折价且数据完整，则计算金额
      if (this.currentProduct.saleType === '折价' &&
        this.currentProduct.compensationQuantity &&
        this.currentProduct.discountPrice) {
        this.calculateActualPayable(this.currentProduct);
      }

      this.showProductEditPopup = true;
    },

    // 校验订单表单
    validateOrderForm () {
      // this.$refs.orderForm.validate().then((res) => {
      //   if (res) {
      //     const existingNotes = this.currentOrder.notes
      //     // 校验通过后，将临时数据更新到表格中
      //     if (this.tempOrderData && this.tempProductData) {
      //       this.tableData = [{
      //         ...this.tempOrderData || this.currentOrder,
      //         notes: existingNotes, // 保留备注
      //         arrivalDate: this.currentOrder.arrivalDate
      //       }];
      //       this.productData = this.tempProductData;
      //       this.updateLocalStorage();
      //       // 关闭弹窗
      //       this.showOrderPopup = false;
      //     }
      //   }
      // }).catch((errors) => {
      //   uni.showToast({
      //     title: '请填写完整订单信息',
      //     icon: 'none',
      //   });
      // });
      this.$refs.orderForm.validate().then(() => {
        const existingNotes = this.currentOrder.notes;

        this.tableData = [{
          ...this.currentOrder,
          notes: existingNotes,
        }];

        this.productData = this.tempProductData?.length > 0 ? this.tempProductData : this.productData;

        this.updateLocalStorage();
        this.showOrderPopup = false;
      }).catch(() => {
        uni.showToast({
          title: '请填写完整订单信息',
          icon: 'none',
        });
      });
    },

    // 校验产品表单
    validateProductForm () {
      this.$refs.productForm.validate().then(res => {
        if (res) {
          const existingReason = this.currentProduct?.reason || '';
          this.currentProduct.reason = existingReason;
          this.saveProductEdit()
          this.updateLocalStorage();
        }
      }).catch(errors => {
        uni.showToast({
          title: '请填写完整订单信息',
          icon: 'none'
        })
      })
    },

    saveOrderEdit () {
      // 同时更新 tableData 和 productData 中的订单信息
      const updatedOrder = { ...this.currentOrder };
      this.$set(this.tableData, this.currentRowIndex, updatedOrder);

      // 如果 productData 中有对应行，也更新
      if (this.productData[this.currentRowIndex]) {
        this.$set(this.productData, this.currentRowIndex, {
          ...this.productData[this.currentRowIndex],
          ...updatedOrder
        });
      }
      this.updateLocalStorage();
      this.showOrderPopup = false;
    },

    saveProductEdit () {
      // 保存前重新计算确保数据准确
      if (this.currentProduct.saleType === '折价') {
        this.calculateActualPayable(this.currentProduct);
      }

      // 更新到产品数据
      this.$set(this.productData, this.currentRowIndex, {
        ...this.currentProduct,
        show: this.currentProduct.saleType === '折价'
      });
      this.showProductEditPopup = false;
    },
    // 时间戳转换
    formatTimestampToYYMMDD (timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear().toString();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hour = ('0' + date.getHours()).slice(-2);
      const minute = ('0' + date.getMinutes()).slice(-2);
      if (this.dateMode === 'date') {
        return `${year}-${month}-${day}`;
      } else if (this.dateMode === 'datetime') {
        return `${year}-${month}-${day} ${hour}:${minute}`;
      } else if (this.dateMode === 'year-month') {
        return `${year}-${month}`;
      }
      return `${year}-${month}-${day}`; // 返回 YYMMDD 格式的字符串
    },
    orderAfterSalesFile (value) {
      console.log('value', value);

    },
    onTextareaInput (value) {
      console.log('value', value.detail.value);

    }
  }
}
</script>

<style scoped lang="scss">
.containerzi {
  background-color: #ffffff
}

.order-item {
  padding: 20rpx;
  border-bottom: 1px solid #eee;
}

.loading-text,
.no-more-text {
  text-align: center;
  color: #888;
  padding: 20rpx 0;
}

/* 隐藏字段样式 */
.hidden-field {
  display: none;
}

::v-deep uni-button {
  margin-left: 0 !important;
  margin-right: 10rpx !important;
  border: none !important;
}

.table-container {
  width: 100%;
}

/* 订单表格专属优化 */
.order-table {

  th,
  td {
    width: auto;

    &:first-child {
      width: auto;
    }
  }

  /* 交替行背景色 */
  tr:nth-child(even) td {
    background-color: #fafafa;
  }

  /* 重要数据突出显示 */
  .highlight {
    color: #e74c3c;
    font-weight: 500;
  }
}

.scroll-view {
  width: 95vw;
  white-space: nowrap;
  padding: 10rpx 0;
}

.mobile-table {
  width: auto;
  min-width: 100%;
  border-collapse: separate;
  border-spacing: 0;

  th,
  td {
    text-align: center;
    padding: 16rpx 24rpx;
    border-bottom: 1px solid #eee;
    font-size: 26rpx;
    line-height: 1.4;
  }

  th {
    background: #f1f2f4;
    color: #333;
    font-weight: 500;
    position: relative;

    &:not(:first-child)::after {
      content: "";
      position: absolute;
      right: 0;
      top: 10%;
      height: 80%;
      width: 1px;
      background: #ddd;
    }
  }

  td {
    color: #666;
    background: #fff;
  }

  .sticky-header {
    position: sticky;
    left: 0;
    z-index: 2;
    width: auto;
  }

  .sticky-col {
    position: sticky;
    left: 0;
    background: #f9f9f9;
    z-index: 1;
  }
}

.nowrap {

  white-space: nowrap;
}

.required-star {
  color: #e74c3c;
  margin-right: 4rpx;
  font-size: 28rpx;
  vertical-align: middle;
}

:required {
  border-left: 4rpx solid #e74c3c;
}


.popup-content {
  padding: 30rpx;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;

  .popup-header {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    text-align: center;
  }

  .order-item {
    padding: 20rpx;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;

    &:active {
      background-color: #f5f5f5;
    }
  }
}


.popup-container {
  width: 100vw;
  height: 100%;
  background-color: #f3f3f3;
  display: flex;
  flex-direction: column;
}

.popup-scroll {
  flex: 1;
  height: auto;
  overflow-y: auto;
}

.popup-content {
  padding: 30rpx;
  background: #fff;
}

.popup-header-fixed {
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1px solid #f5f5f5;
  position: sticky;
  top: 0;
  z-index: 10;
}

::v-deep .up-form-item__error {
  color: #e74c3c;
  font-size: 24rpx;
  margin-top: 8rpx;
}




.order-item {
  padding: 24rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    background-color: #f5f5f5 !important;
  }
}

.order-info {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;
  line-height: 1.5;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-label {
  color: #666;
  min-width: 140rpx;
}

.order-value {
  color: #333;
  font-weight: 500;
}

.loading-text,
.no-more-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 26rpx;

  text {
    margin-top: 16rpx;
  }
}

.u-page {
  padding: 0;
}

.u-cell-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 8rpx;
}

.u-cell-group__title__text {
  font-weight: bold;
}



.popup-containerd {
  background-color: #f5f5f5;
  padding: 0 20rpx;
  height: calc(100vh - 100rpx);
}

.popup-scroll {
  height: 100%;
}

.search-box {
  //margin-bottom: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 10rpx 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.popup-scroll {
  height: calc(100% - 80rpx);
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  display: flex;
  flex-direction: column;
  transition: all 0.2s;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.99);
  }
}

.order-info {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-label {
  color: #666;
  width: 140rpx;
}

.order-value {
  color: #333;
  flex: 1;
  font-weight: 500;
}

.order-arrow {
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
}

.load-more,
.no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 26rpx;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.empty-tip {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
}
</style>
